﻿using Core.Infarastructure;
using Core.Infarastructure.Structs;
using Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Helpers
{
    /// <summary>
    /// Provide a logic of finding free space between stacks
    /// </summary>
    public class PutHeroOnGameBoard
    {
        /// <summary>
        /// Finds a the place on the drawing field between stacks where hero can be putted
        /// </summary>
        /// <param name="stacks"></param>
        /// <returns></returns>
        public static Point Put(List<Stack> stacks)
        {
            var heroCoordinate = new Point();
            var sortedStacks = SortStacks(stacks);
            for (var i = 1; i < sortedStacks.Count; i++ )
            {
                if ((sortedStacks[i].XPosition - sortedStacks[i - 1].XPosition) > Constants.STACK_SIZE)
                {
                    heroCoordinate.X = sortedStacks[i - 1].XPosition + Constants.STACK_SIZE;
                    heroCoordinate.Y = sortedStacks[i - 1].YPosition;
                }
            }
            return heroCoordinate;
        }
        /// <summary>
        /// Sorted the set of stacks
        /// </summary>
        /// <param name="stacks"></param>
        /// <returns></returns>
        private static List<Stack> SortStacks(List<Stack> stacks)
        { 
            List<Stack> sortedStacks = new List<Stack>(stacks);

            sortedStacks.Sort(CoordinatesComparer);

            return sortedStacks;
        }

        private static int CoordinatesComparer(Stack x, Stack y)
        {
            if (x.XPosition < y.XPosition)
            {
                return -1;
            }
            if (x.XPosition == y.XPosition)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
    }
}
